<?php namespace Phpcmf\Model\Comment;

// 评论插件
class Mform extends \Phpcmf\Model
{


    // 初始化模块
    public function _init($module, $fid, $siteid, $comment) {
        $this->fid = $fid;
        $this->form = $module['form'][$fid];
        $this->module = $module;
        $this->siteid = $siteid;
        $this->mytable = $siteid.'_'.$module['dirname'].'_form_'.$fid;
        $this->comment = $comment;
        $this->dirname = $module['dirname'];
        return $this;
    }

    // 获取主数据
    public function get_row($id, $myid = 'id') {

        if (!$id) {
            return [];
        }

        $data = $this->table($this->mytable)->get($id);
        if (!$data) {
            return [];
        }

        $data['url'] = dr_url_prefix(\Phpcmf\Service::L('router')->mform_show_url($this->fid, $id, $this->dirname), $this->dirname, $this->siteid, 0);
        $data['is_comment'] = isset($data['is_comment']) ? $data['is_comment'] : 0;

        $data2 = $this->table($this->mytable.'_data_'.intval($data['tableid']))->get($id);
        if ($data2) {
            $data = $data + $data2;
        }

        return $data;
    }

    // 获取评论索引数据
    public function get_comment_index($cid) {

        if (!$cid) {
            return [];
        }

        $rt = $this->table($this->mytable.'_comment_index')->where('cid', $cid)->getRow();
        if (!$rt) {
            // 不存在就创建它
            $rt = [
                'cid' => $cid,
                'sort1' => 0,
                'sort2' => 0,
                'sort3' => 0,
                'sort4' => 0,
                'sort5' => 0,
                'sort6' => 0,
                'sort7' => 0,
                'sort8' => 0,
                'sort9' => 0,
                'oppose' => 0,
                'support' => 0,
                'avgsort' => 0,
                'comments' => 0,
            ];
            $rt['id'] = $this->table($this->mytable.'_comment_index')->insert($rt);
        }

        return $rt;
    }

    // 提交评论
    // $value 主题信息和回复人；$data评论内容和点评内容；$my自定义字段
    public function insert_comment($value, $data, $my = []) {

        $insert = [];
        $insert['cid'] = (int)$value['index']['id'];
        $insert['cuid'] = (int)$value['index']['uid'];
        //$insert['catid'] = (int)$value['index']['catid'];
        $insert['uid'] = (int)$value['member']['uid'];
        $insert['reply'] = (int)$value['reply_id'];
        $insert['in_reply'] = 0;
        $insert['status'] = $value['status'];
        $insert['author'] = $insert['uid'] ? ($value['member']['name'] ? $value['member']['name'] : $value['member']['username']) : '游客';
        $insert['content'] = $data['content'];
        $insert['support'] = $insert['oppose'] = $insert['avgsort'] = 0;
        $insert['inputip'] = \Phpcmf\Service::L('input')->ip_info();
        $insert['inputtime'] = $data['inputtime'] ? $data['inputtime'] : SYS_TIME;
        //$insert['orderid'] = (int)$value['orderid'];

        // 点评选项值
        $_value = [];
        $_avgsort = 0;
        for ($i = 1; $i <= 9; $i++) {
            $insert['sort'.$i] = isset($data['review'][$i]) ? (int)$data['review'][$i] : 0;
            $_avgsort+= $insert['sort'.$i];
            $insert['sort'.$i] && $_value[$i] = $insert['sort'.$i];
        }

        if ($_avgsort) {
            // 算法类别
            $dl = empty($this->comment['review']['point']) || $this->comment['review']['point'] < 0 ? 0 : $this->comment['review']['point']; //小数点位数
            // 分别计算各个选项分数
            $insert['avgsort'] = round(($_avgsort / dr_count($_value)), $dl);
        }

        // 自定义字段入库
        $my && $insert = array_merge($insert, $my);

        $rt = $this->table($this->mytable.'_comment')->insert($insert);
        if (!$rt['code']) {
            return $rt;
        }

        // 评论成功返回id
        $id = $rt['code'];

        if (!$insert['status']) {
            // 需要审核时直接返回
            \Phpcmf\Service::M('member')->admin_notice($this->siteid, 'content', \Phpcmf\Service::C()->member, dr_lang('%s表单%s: 新%s审核', $this->module['name'], $this->form['name'], $this->comment['cname']), $this->dirname.'/'.$this->fid.'_comment_verify/edit:cid/'.$insert['cid'].'/id/'.$id);
            return dr_return_data($id, 'verify');
        } else {
            // 直接通过的评论
            $insert['id'] = $id;
            $this->verify_comment($insert);
            return dr_return_data($id, 'ok');
        }

    }

    // 审核评论
    public function verify_comment($row) {

        if (!$row) {
            return;
        }

        $id = (int)$row['id'];

        // 当前是未审核状态时才更新状态
        if ($row['status'] != 1) {
            // 变更审核状态
            $this->db->table($this->mytable.'_comment')->where('id', $id)->update(['status' => 1]);
        }

        // 提醒
        /*暂时不要回复站内信通知
        $row['reply']
            ? \Phpcmf\Service::M('member')->notice($row['uid'], 2, dr_lang('评论被人回复'), '/index.php?s='.MOD_DIR.'&c=show&id='.$row['cid'])
            : \Phpcmf\Service::M('member')->notice($row['cuid'], 2, dr_lang('收到了新的评论'), '/index.php?s='.MOD_DIR.'&c=show&id='.$row['cid']);
        */
        
	   if ($row['reply'] == '0') {
		   \Phpcmf\Service::M('member')->notice($row['uid'], 2, dr_lang('评论被人回复'), '/index.php?s='.MOD_DIR.'&c=show&id='.$row['cid']);
	   } else {
		   //获取评论人的ID
		   $pinglunid = $this->db->table($this->mytable.'_comment')
		   ->where('id', $row['reply'])->where('status', 1)
		   ->get()->getRowArray();
		   \Phpcmf\Service::M('member')->notice($pinglunid['uid'], 2, dr_lang('评论被人回复'), '/index.php?s='.MOD_DIR.'&c=show&id='.$row['cid']);
	   }
	

        // 统计评论总数
        $this->comment_update_total($row);

        // 回复评论时，将主题设置为存在回复状态
        $row['reply'] && $this->table($this->mytable.'_comment')->update($row['reply'], ['in_reply' => 1]);

        // 增减金币
        $score = \Phpcmf\Service::C()->_get_auth_value('comment_score', dr_member_info($row['uid']));
        $score && \Phpcmf\Service::M('member')->add_score($row['uid'], $score, dr_lang('%s表单%s：发布%s', $this->module['name'], $this->form['name'], $this->comment['cname']), $row['curl']);

        // 增减经验
        $exp = \Phpcmf\Service::C()->_get_auth_value('comment_exp', dr_member_info($row['uid']));
        $exp && \Phpcmf\Service::M('member')->add_experience($row['uid'], $exp, dr_lang('%s表单%s：发布%s', $this->module['name'], $this->form['name'], $this->comment['cname']), $row['curl']);

        // 更新评分
        $this->comment_update_review($row);

        // 执行通知
        \Phpcmf\Service::M('member')->todo_admin_notice($this->dirname.'/'.$this->fid.'_comment_verify/edit:cid/'.$row['cid'].'/id/'.$row['id'], $this->siteid);

        // 获取文章标题
        $index = $this->table($this->mytable)->get($row['cid']);
        $row['title'] = $index['title'];
        $row['index'] = $index;
        $row['comment_uid'] = $row['uid'];
        $row['comment_author'] = $row['author'];

        
		
		if($index['title']){
			$title = $index['title'];
		} else {
			$title = dr_strcut(dr_clearhtml($index['neirong']), 10);
		}
		$data = \Phpcmf\Service::M()->table('app_weixin_shezhi_tongzhi')->where('id', 1)->getRow();
		if (!$data) {
			$this->_admin_msg(0, dr_lang('模块#%s不存在', 'weixin'));
		}
		
		
		$data['setting'] = dr_string2array($data['setting']);
		if (!isset($data['setting']['pages'])) {
			$data['setting']['pages'] = [];
		}
		$muban = $data['setting']['pages'];
		//dr_debug('文件名$muban称', $muban);
		$biaoqiana = $muban['biaoqiana'];
		$biaoqianb = $muban['biaoqianb'];
		$biaoqianc = $muban['biaoqianc'];

		if($row['cuid'] !=$this->uid){
			if($row['reply'] == '0'){
				// 评论通过后的通知消息
				/*$row['uid'] = $index['uid'];
				$row['url'] = '/index.php?s='.MOD_DIR.'&c=son&id='.$row['cid'];
				dr_debug('文件$row', $row);
				\Phpcmf\Service::L('Notice')->send_notice('module_form_'.$this->dirname.'_1', $row);*/
				// 挂钩点 评论完成之后
				\Phpcmf\Hooks::trigger('mform_comment_after', $row);
				$user=dr_member_info($this->uid);
				$memberuid = $user['username'];
				$www = SITE_URL;
				\Phpcmf\Service::L('Notice')->send_notice_user("评论", $index['uid'], [], [
					'weixin' => [
						'tpl_content' => [
							'id' => $muban['pinglun'],
							'param' => [
								$biaoqiana => [
								  'value' => dr_date(SYS_TIME),
								  'color' => '#173177',
								],
								$biaoqianb => [
								  'value' => '【'.$title.'】',
								  'color' => '#173177',
								],
								$biaoqianc => [
								  'value' => $memberuid.' - 回复：'.dr_strcut(dr_clearhtml($row['content']), 50),
								  'color' => '#173177',
								],
							],
							'url' => $www.'/index.php?s='.MOD_DIR.'&c=son&id='.$row['cid'],
						],
					],
				]);
				
				
				
				
			} else {
				
				/*$row['uid'] = $pinglunid['uid'];
				$row['url'] = '/index.php?s='.MOD_DIR.'&c=son&id='.$row['cid'];
				\Phpcmf\Service::L('Notice')->send_notice('module_form_'.$this->dirname.'_1', $row);*/
				
				$user=dr_member_info($this->uid);
				$memberuid = $user['username'];
				$www = SITE_URL;
				\Phpcmf\Service::L('Notice')->send_notice_user("评论", $pinglunid['uid'], [], [
					'weixin' => [
						'tpl_content' => [
							'id' => $muban['pinglun'],
							'param' => [
								'keyword1' => [
								  'value' => dr_date(SYS_TIME),
								  'color' => '#173177',
								],
								'keyword2' => [
								  'value' => '【'.$title.'】',
								  'color' => '#173177',
								],
								'keyword3' => [
								  'value' => $memberuid.' - 回复：'.dr_strcut(dr_clearhtml($row['content']), 50),
								  'color' => '#173177',
								],
							],
							'url' => $www.'/index.php?s='.MOD_DIR.'&c=son&id='.$row['cid'],
						],
					],
				]);
				
			}
			
			//\Phpcmf\Service::L('Notice')->send_notice('mform_comment_verify_1', $row);
		}


        /*// 评论通过后的通知消息
        $row['url'] = $index['url'];
        \Phpcmf\Service::L('Notice')->send_notice('mform_comment_verify_1', $row);

        // 评论后通知内容作者
        $row['uid'] = $index['uid'];
		$row['url'] = $index['url'];
        \Phpcmf\Service::L('Notice')->send_notice('mform_comment_verify_2', $row);
		
		// 评论后通知内容作者
		$row['uid'] = $index['uid'];
		$row['url'] = '/index.php?s='.MOD_DIR.'&c=son&id='.$row['cid'];
		\Phpcmf\Service::L('Notice')->send_notice('module_form_'.$this->dirname.'_1', $row);*/

    }

    // 获取评论列表
    public function get_comment_result($cid, $order, $page, $pagesize, $total, $field) {

        if (!$cid) {
            return [];
        }

        if(!$this->uid){
			$ptid=0;
			$puid=0;
		} else {
			$heiuiddata = \Phpcmf\Service::M()->table('1_quan_hei_uid')->where('uid', $this->uid)->getAll();
			$heiptiddata = \Phpcmf\Service::M()->table('1_quan_hei_pinglun')->where('uid', $this->uid)->getAll();
			$unheiuiddata = [];
			foreach ($heiuiddata as $v => $data) {
				$unheiuiddata[] = $data['touid'];
			}
			//$puid = implode(',',$unheiuiddata);
			//$puid = $unheiuiddata;
			if(count($unheiuiddata)>0){
			    $puid = $unheiuiddata;
			    //$puid =$puid;
			} else {
			    $puid =['0'];
			}
			//$puid=[''.$puid.''];
			$unheiptiddata = [];
			foreach ($heiptiddata as $v => $data) {
				$unheiptiddata[] = $data['pid'];
			}
			//$puid = implode(',',$unheiptiddata);
			//$ptid = $unheiptiddata;
			if(count($unheiptiddata)>0){
			    $ptid = $unheiptiddata;
			} else {
			    $ptid = ['0'];
			}
		}

		

        $list = $this->db->table($this->mytable.'_comment')
            ->where('cid', $cid)->where('reply', 0)->where('status', 1)
            ->limit($pagesize, $pagesize * ($page - 1))
            ->whereNotIn('id', $ptid)
            ->whereNotIn('uid', $puid)
            //->orderBy($order)
			//改变评论顺序
			->orderBy('inputtime ASC,id ASC')
            ->get()->getResultArray();
        // 微信
		

        if ($list) {
            $dfield = \Phpcmf\Service::L('Field')->app($this->dirname);
            foreach ($list as $i => $t) {
                $reply = !$t['in_reply'] ? [] : $this->db->table($this->mytable.'_comment')
                    ->where('cid', $cid)->where('reply', $t['id'])->where('status', 1)
                    ->whereNotIn('id', $ptid)
                    ->whereNotIn('uid', $puid)
                    ->orderBy($order)
                    ->get()->getResultArray();
                    foreach ($reply as $b => $v) {
                                $userweixin=\Phpcmf\Service::M()->db->table('member_oauth')->where('uid', $reply[$b]['uid'])->get()->getRowArray();
                        		$user=dr_member_info($reply[$b]['uid']);
                        		//dr_debug('$user', $user);
                        		if ($user['name']) {
                        			$reply[$b]['mingcheng'] = $user['name']; 
                        		} elseif ($userweixin['nickname']) {
                        			$reply[$b]['mingcheng'] = $userweixin['nickname']; 
                        		} else {
                        			$reply[$b]['mingcheng'] = $user['username'];
                        		}
                        		//用户组
                        		foreach ($user['group'] as $t) {
                        			$reply[$b]['yonghuzu'] = $t['group_name'];
                        		}
                        		//归属地
                        		$ip=\Phpcmf\Service::L('ip')->address($reply[$i]['inputip']);
                        		if ($ip == "未知地区"){
                        			$reply[$b]['guishudi'] = "中国";
                        		} else{
                        			$reply[$b]['guishudi'] = $ip;
                        		}
                        		//评论内容
        		        		$reply[$b]['content'] = dr_code2html($reply[$b]['content']);
                        		//时间
                        		$reply[$b]['inputtimes'] = dr_date($reply[$b]['inputtime'], "Y-m-d (H:i:s) ");
                        		//头像
                        		$reply[$b]['touxiang'] = dr_avatar($reply[$b]['uid']);
                                //$reply[$b] = $dfield->format_value($field, $v, 1);
                            }
                if ($field) {
                    // 格式化显示自定义字段内容
                    
                    $list[$i] = $dfield->format_value($field, $t, 1);
                    if ($reply) {
                        foreach ($reply as $b => $v) {
                            
                            $reply[$b] = $dfield->format_value($field, $v, 1);
                        }
                    }
                }
                //微信
                $userweixin=\Phpcmf\Service::M()->db->table('member_oauth')->where('uid', $list[$i]['uid'])->get()->getRowArray();
                //评论数量
                $pinglunshu = \Phpcmf\Service::M()->db->table('1_quan_form_son_comment')->where('reply', $list[$i]['id'])->countAllResults();
        		$user=dr_member_info($list[$i]['uid']);
        		//dr_debug('$user', $user);
        		if ($user['name']) {
        			$list[$i]['mingcheng'] = $user['name']; 
        		} elseif ($userweixin['nickname']) {
        			$list[$i]['mingcheng'] = $userweixin['nickname']; 
        		} else {
        			$list[$i]['mingcheng'] = $user['username'];
        		}
        		//用户组
        		foreach ($user['group'] as $t) {
        			$list[$i]['yonghuzu'] = $t['group_name'];
        		}
        		//归属地
        		$ip=\Phpcmf\Service::L('ip')->address($list[$i]['inputip']);
        		if ($ip == "未知地区"){
        			$list[$i]['guishudi'] = "中国";
        		} else{
        			$list[$i]['guishudi'] = $ip;
        		}
        		//评论数量
        		$list[$i]['pinglunshu'] =  $pinglunshu;
        		//评论内容
        		
        		$list[$i]['content'] = dr_code2html($list[$i]['content']);
        		//时间
        		$list[$i]['inputtimes'] = dr_date($list[$i]['inputtime'], "Y-m-d (H:i:s) ");
        		//头像
        		$list[$i]['touxiang'] = dr_avatar($list[$i]['uid']);

                $list[$i]['rlist'] = $reply;
                //微信
                
            }
            
        }
        


        !$total && $total = $this->db->table($this->mytable.'_comment')->where('cid', $cid)->where('reply', 0)->where('status', 1)->countAllResults();

        return [$list, $total];
    }


    // 删除评论
    public function delete_comment($id, $cid = 0) {

        if (!$id) {
            return 0;
        }

        $data = $this->table($this->mytable.'_comment')->get($id);
        if (!$data) {
            return -1;
        }

        // 删除评论数据
        $this->db->table($this->mytable.'_comment')->where('id', $id)->delete();
        $this->db->table($this->mytable.'_comment')->where('reply', $id)->delete();


        // 统计评论总数
        $this->comment_update_total($data);

        // 删除附件
        SYS_ATTACHMENT_DB  && \Phpcmf\Service::M('Attachment')->id_delete(
            $data['uid'],
            [$id],
            $this->dbprefix($this->mytable.'_comment-'.($data['reply'] ? $data['reply'] : $id))
        );

        // 更新评分
        $this->comment_update_review($data);

        return 1;
    }

    // 更新统计
    public function comment_update_total($row) {

        if (!$this->comment || !$row) {
            return;
        }

        $cid = (int)$row['cid'];
        // 统计评论总数
        if (!$this->comment['ct_reply']) {
            $total = $this->db->table($this->mytable.'_comment')->where('cid', $cid)->where('reply', 0)->where('status', 1)->countAllResults();
        } else {
            $total = $this->db->table($this->mytable.'_comment')->where('cid', $cid)->where('status', 1)->countAllResults();
        }

        $this->table($this->mytable)->update($cid, ['comments' => $total]);
        $this->table($this->mytable.'_comment_index')->update($row['id'], ['comments' => $total]);

    }

    // 更新评分
    public function comment_update_review($row) {

        // 只在开启时更新
        if (!$this->comment['review']) {
            return;
        }

        $id = (int)$row['id'];
        $cid = (int)$row['cid'];

        // 更新点评数据
        $review = $set = [];
        $_avgsort = 0;
        for ($i = 1; $i <= 9; $i++) {
            if ($row['sort'.$i]) {
                $review[$i] = $row['sort'.$i];
                $set['sort'.$i] = 0;
                $_avgsort += $review[$i];
            }
        }

        // 分值不存在时不更新
        if (!$review) {
            return ;
        }

        // 统计总的点评数
        $builder = $this->db->table($this->mytable.'_comment');
        $builder->where('cid', $cid);
        $builder->selectSum('status', 'num');
        foreach($review as $i => $val) {
            $builder->selectSum('sort'.$i);
        }

        // 不统计回复
        if (!\Phpcmf\Service::C()->module['comment']['ct_reply']) {
            $builder->where('reply', 0);
        }

        $grade = $builder->where('status', 1)->get()->getRowArray();

        if (!$grade) {
            return;
        }

        // 算法类别
        $st = round((int)$this->comment['review']['score'] / 5); //显示分数制 5分，10分，百分
        $dl = empty($this->comment['review']['point']) || $this->comment['review']['point'] < 0 ? 0 : $this->comment['review']['point']; //小数点位数

        // 分别计算各个选项分数
        foreach($review as $i => $aaaaa) {
            $flag = 'sort'.$i;
            $set[$flag] = $grade[$flag] ? round( ($grade[$flag] / $grade['num'] * $st), $dl) : 0;
            $set['avgsort']+= $set[$flag];
        }

        // 总表的平均分
        $set['avgsort'] = round(($set['avgsort'] / dr_count($review)), $dl);

        // 本记录的
        $avgsort = round(($_avgsort / dr_count($review)) * $st, $dl);

        // 更新到索引表
        $this->db->table($this->mytable.'_comment')->where('id', $id)->update(['avgsort' => $avgsort]);

        // 更新到关联主表
        $this->table($this->mytable)->update($cid, [
            'avgsort' => $set['avgsort'],
        ]);

        // 更新到索引表
        $this->db->table($this->mytable.'_comment_index')->where('cid', $cid)->update($set);

    }

}